package com.ruoyi.business.websocket;

import com.ruoyi.business.utils.WebSocketUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @Author: sgchen
 * @Description: 向app端实时推送业务状态信息
 * @Date: 2025/5/6
 **/
@Component
@ServerEndpoint(value = "/websocket/sign/{expireUuid}")
public class WebSocketController {

    // session超时时间（毫秒）
    public static final int sessionTimeout = 120000;

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketController.class);

    /**
     * @Author: sgchen
     * @Description: 加入连接
     * @Date: 2025/5/6
     * @Param expireUuid: 签字的id
     * @Param session:
     * @Return:
     **/
    @OnOpen
    public void onOpen(@PathParam("expireUuid") String expireUuid, Session session) {
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        if(!redisCache.hasKey(expireUuid)){
            WebSocketUtil.sendMessage(session, "二维码已失效，请重新获取");
            try {
                session.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        LOGGER.info("[{}]加入连接!", expireUuid);
        WebSocketUtil.remoteAllInValidSession();
        // 60S后过期
        session.setMaxIdleTimeout(sessionTimeout);
        WebSocketUtil.addSession(expireUuid, session);
    }

    /**
     * @Author: sgchen
     * @Description: 断开连接
     * @Date: 2025/5/6
     * @Param expireUuid:
     * @Param session:
     * @Return:
     **/
    @OnClose
    public void onClose(@PathParam("expireUuid") String expireUuid, Session session) {
        LOGGER.info("[{}]断开连接!", expireUuid);
        WebSocketUtil.remoteSession(expireUuid);
    }

    /**
     * @Author: sgchen
     * @Description: 发送消息
     * @Date: 2025/5/6
     * @Param expireUuid: 签字的id
     * @Param message: 消息
     * @Return:
     **/
    @OnMessage
    public void OnMessage(@PathParam("expireUuid") String expireUuid, String message) {
        Session session = WebSocketUtil.ONLINE_SESSION.get(expireUuid);
        if(session==null){
            return;
        }
        String messageInfo = "服务器对[" + expireUuid + "]发送消息：" + message;
        LOGGER.info(messageInfo);
        //发送普通信息
        WebSocketUtil.sendMessage(session, message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        LOGGER.error("{}异常:", session.getId(), throwable);
        session.close();
    }
}


